<template>
  <view class="health-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <image src="/static/logo.png" mode="aspectFit" class="logo"></image>
      <text class="title"> 健康档案 </text>
    </view>

    <!-- 选项卡 -->
    <view class="tabs">
      <view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', activeTab === index ? 'active' : '']"
        @click="activeTab = index">
        {{ tab }}
      </view>
    </view>

    <!-- 内容区 -->
    <scroll-view scroll-y class="content">
      <!-- 病历记录 -->
      <view v-if="activeTab === 0" class="tab-content">
        <button class="add-btn" @click="showAddDialog('medical')">
          <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          添加记录
        </button>

        <view class="record-list">
          <view v-for="item in recordStore.getMedicalRecordList" :key="item.id" class="record-card">
            <view class="card-header">
              <text class="date">{{ formatData(item.time) }}</text>
              <text class="hospital">{{ item.hospital }} · {{ item.department }}</text>
            </view>
            <view class="diagnosis">{{ item.diagnosis }}</view>
            <view class="advice">{{ item.advice }}</view>
            <view class="card-footer">
              <button class="action-btn" @click="viewDetail(item, 'medical')">查看详情</button>
              <button class="action-btn delete" @click="deleteRecord(item, 'medical')">删除记录</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 用药记录 -->
      <view v-if="activeTab === 1" class="tab-content">
        <button class="add-btn" @click="showAddDialog('medication')">
          <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          添加记录
        </button>

        <view class="medication-list">
          <view v-for="item in recordStore.getMedicationList" :key="item.id" class="medication-card">
            <view class="card-header">
              <text class="date">{{ formatData(item.startDate) }}</text>
              <text class="name">{{ item.medicationName }}</text>
            </view>
            <view class="details">
              <text>剂量: {{ item.dosage }}</text>
              <text>频率: {{ item.frequency }}</text>
            </view>
            <view class="purpose">{{ item.drugDiscription }}</view>
            <view class="card-footer">
              <button class="action-btn" @click="viewDetail(item, 'medication')">查看详情</button>
              <button class="action-btn delete" @click="deleteRecord(item, 'medication')">删除记录</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 体检报告 -->
      <!-- <view v-if="activeTab === 2" class="tab-content">
        <button class="upload-btn" @click="uploadReport">
          <uni-icons type="upload" size="16" color="#fff"></uni-icons>
          上传报告
        </button>

        <view class="report-list">
          <view v-for="item in healthReports" :key="item.id" class="report-card" @click="viewReport(item)">
            <view class="card-header">
              <text class="date">{{ item.date }}</text>
              <text class="type">{{ item.type }}</text>
            </view>
            <view class="institution">{{ item.institution }}</view>
            <view class="file-info">
              <uni-icons type="paperclip" size="16" color="#409eff"></uni-icons>
              <text class="file-name">{{ item.fileName }}</text>
            </view>
          </view>
        </view>
      </view> -->
    </scroll-view>

    <!-- 添加记录弹窗 -->
    <uni-popup ref="addDialog" type="dialog" >
      <uni-popup-dialog mode="base" :title="dialogTitle" @close="closeDialog" @confirm="saveRecord">
        <view class="dialog-content">
          <uni-forms :model="currentForm" label-position="top">
            <!-- 病历表单 -->
            <template v-if="dialogType === 'medical'">
              <uni-forms-item label="就诊日期">
                <uni-datetime-picker v-model="currentForm.time" />
              </uni-forms-item>
              <uni-forms-item label="医院名称">
                <uni-easyinput v-model="currentForm.hospital" placeholder="请输入医院名称" />
              </uni-forms-item>
              <uni-forms-item label="科室">
                <uni-easyinput v-model="currentForm.department" placeholder="请输入科室" />
              </uni-forms-item>
              <uni-forms-item label="诊断结果">
                <uni-easyinput type="textarea" v-model="currentForm.diagnosis" placeholder="请输入诊断结果" />
              </uni-forms-item>
              <uni-forms-item label="医嘱">
                <uni-easyinput type="textarea" v-model="currentForm.advice" placeholder="请输入医嘱" />
              </uni-forms-item>
            </template>

            <!-- 用药表单 -->
            <template v-if="dialogType === 'medication'">
              <uni-forms-item label="用药日期">
                <uni-datetime-picker v-model="currentForm.startDate" />
              </uni-forms-item>
              <uni-forms-item label="药品名称">
                <uni-easyinput v-model="currentForm.medicationName" placeholder="请输入药品名称" />
              </uni-forms-item>
              <uni-forms-item label="剂量">
                <uni-easyinput v-model="currentForm.dosage" placeholder="请输入剂量" />
              </uni-forms-item>
              <uni-forms-item label="服用频率">
                <uni-easyinput v-model="currentForm.frequency" placeholder="如：每日一次" />
              </uni-forms-item>
              <uni-forms-item label="用途">
                <uni-easyinput v-model="currentForm.drugDiscription" placeholder="请输入用途" />
              </uni-forms-item>
            </template>
          </uni-forms>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 详细信息弹窗 -->
    <!-- 增强版详情弹窗 -->
    <uni-popup ref="showDialog" type="dialog" :mask-click="false">
      <uni-popup-dialog mode="base" title="详细信息" :closeable="true" :background="dialogBgColor">
        <view class="detail-container" v-if="dialogType.value === 'medication' && recordStore.getSelectedMedication">
          <!-- 药品信息卡片 -->
          <view class="medication-card">
            <view class="card-header">
              <view class="pill-icon">
                <uni-icons type="star-filled" size="20" color="#fff"></uni-icons>
              </view>
              <text class="card-title">{{ recordStore.getSelectedMedication.medicationName }}</text>
            </view>

            <view class="card-section">
              <view class="section-header">
                <uni-icons type="time" size="16" color="#f56c6c"></uni-icons>
                <text class="section-title">用药周期</text>
              </view>
              <text class="date-range">
                {{ formatData(recordStore.getSelectedMedication.startDate) }}
                <uni-icons type="arrowright" size="12" color="#999"></uni-icons>
                {{ formatData(recordStore.getSelectedMedication.endDate) }}
              </text>
            </view>

            <view class="card-section">
              <view class="section-header">
                <uni-icons type="clock" size="16" color="#67c23a"></uni-icons>
                <text class="section-title">服用说明</text>
              </view>
              <view class="dose-info">
                <text class="dose-tag">{{ recordStore.getSelectedMedication.frequency }}</text>
                <text class="dose-tag">剂量: {{ recordStore.getSelectedMedication.dosage }}</text>
              </view>
            </view>

            <view class="card-section">
              <view class="section-header">
                <uni-icons type="info" size="16" color="#909399"></uni-icons>
                <text class="section-title">药物说明</text>
              </view>
              <text class="description-text">{{ recordStore.getSelectedMedication.drugDiscription }}</text>
            </view>

            <!-- 操作按钮 -->
            <view class="action-bar">
              <button class="action-button edit" @click="editRecord">
                <uni-icons type="edit" size="14" color="#409eff"></uni-icons>
                <text>编辑</text>
              </button>
              <button class="action-button delete" @click="confirmDelete">
                <uni-icons type="trash" size="14" color="#f56c6c"></uni-icons>
                <text>删除</text>
              </button>
            </view>
          </view>
        </view>

        <view class="detail-container" v-else-if="recordStore.getSelectedMedicalRecord">
          <!-- 病历信息卡片 -->
          <view class="medical-card">
            <view class="card-header">
              <uni-icons type="hospital" size="20" color="#fff"></uni-icons>
              <text class="card-title">{{ recordStore.getSelectedMedicalRecord.hospital }}</text>
            </view>

            <view class="card-section">
              <view class="section-header">
                <uni-icons type="calendar" size="16" color="#409eff"></uni-icons>
                <text class="section-title">就诊时间</text>
              </view>
              <text class="record-date">{{ formatData(recordStore.getSelectedMedicalRecord.time) }}</text>
            </view>

            <view class="card-section">
              <view class="section-header">
                <uni-icons type="list" size="16" color="#67c23a"></uni-icons>
                <text class="section-title">科室</text>
              </view>
              <text class="record-department">{{ recordStore.getSelectedMedicalRecord.department }}</text>
            </view>

            <view class="card-section diagnosis">
              <view class="section-header">
                <uni-icons type="alert" size="16" color="#e6a23c"></uni-icons>
                <text class="section-title">诊断结果</text>
              </view>
              <text class="diagnosis-text">{{ recordStore.getSelectedMedicalRecord.diagnosis }}</text>
            </view>

            <view class="card-section advice">
              <view class="section-header">
                <uni-icons type="help" size="16" color="#909399"></uni-icons>
                <text class="section-title">医嘱建议</text>
              </view>
              <text class="advice-text">{{ recordStore.getSelectedMedicalRecord.advice }}</text>
            </view>

            <!-- 操作区域 -->
            <!-- <view class="action-bar">
              <button class="action-button edit" @click="editRecord">
                <uni-icons type="edit" size="14" color="#409eff"></uni-icons>
                <text>编辑</text>
              </button>
              <button class="action-button delete" @click="confirmDelete">
                <uni-icons type="trash" size="14" color="#f56c6c"></uni-icons>
                <text>删除</text>
              </button>
            </view> -->

          </view>
        </view>

      
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRecordStore } from '../../store/modules/useRecordStore'
import {useUserStore} from '../../store/modules/useUserStore'
import {useBindingStore} from '../../store/modules/useBindingStore'

const userStore = useUserStore()
const bindingStore = useBindingStore()

// 使用Pinia存储
const recordStore = useRecordStore()

// 页面状态
const activeTab = ref(0)
const tabs = ref(['病历记录', '用药记录'])

// 弹窗状态
const addDialog = ref(null)
const showDialog = ref(null)
const dialogType = ref('medical')
const dialogTitle = ref('添加病历记录')

// 表单数据 - 直接使用store中的临时记录
const currentForm = ref({})


// 体检报告数据（示例）
const healthReports = ref([
  {
    id: 1,
    date: '2023-04-20',
    type: '年度体检',
    institution: '北京体检中心',
    fileName: '2023年度体检报告.pdf',
    filePath: ''
  },
  {
    id: 2,
    date: '2023-01-05',
    type: '血常规',
    institution: '社区医院',
    fileName: '血常规检查结果.pdf',
    filePath: ''
  }
])


const formatData = (data) => {
  if (!data) {
    return ''
  }
  return data.split('T')[0]
}


/**
 * 组件挂载时加载数据
 * 注意：实际项目中应从接口获取当前用户ID
 */
onMounted(async () => {
  try {
    let userId;
    const role = userStore.getRole;
    if(role == 'older'){
      userId =  userStore.curUserId;
    }else{
      userId = bindingStore.getCurBindingId ;
    }

    console.log('userId:', userId);
    if(!userId){
      throw new Error('fetch data error')
    }
    await recordStore.setCurUserId(userId);

    await recordStore.fetchMedicationList(userId)
    await recordStore.fetchMedicalRecordList(userId)
  } catch (error) {
    uni.showToast({ title: '数据加载失败', icon: 'none' })
    console.error('数据加载失败:', error)
  }
})

/**
 * 显示添加弹窗
 * @param {string} type - 记录类型 ('medical' | 'medication')
 */
const showAddDialog = (type) => {
  dialogType.value = type
  dialogTitle.value = type === 'medical' ? '添加病历记录' : '添加用药记录'

  // 初始化表单数据 - 使用空对象或现有记录（编辑场景）
  currentForm.value = {
    userId: recordStore.getCurUserId || 1, // 从store获取
    time: new Date().toISOString().split('T')[0], // 默认当前日期
    medicationName: '',
    dosage: '',
    frequency: '',
    drugDiscription: '',
    hospital: '',
    department: '',
    diagnosis: '',
    advice: ''
  }

  addDialog.value.open()
}

/**
 * 保存记录
 * 处理新增记录的业务逻辑
 */
const saveRecord = async () => {
  try {
    console.log('saveRecord:', currentForm.value)
    if (dialogType.value === 'medical') {
      console.log('saveRecord:', recordStore.getCurUserId)
      console.log('saveRecord:', )
      await recordStore.addMedicalRecord(currentForm.value)

      uni.showToast({ title: '病历添加成功' })
    } else {
      await recordStore.addMedication(currentForm.value)
      uni.showToast({ title: '用药记录添加成功' })
    }
    closeDialog()
  } catch (error) {
    uni.showToast({ title: '保存失败，请重试', icon: 'none' })
    console.error('保存记录失败:', error)
  }
}

/**
 * 删除记录
 * @param {Object} item - 待删除的记录对象
 * @param {string} type - 记录类型
 */
const deleteRecord = (item, type) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          if (type === 'medical') {
            await recordStore.delMedicalRecord(item.id)
            uni.showToast({ title: '病历删除成功' })
          } else {
            await recordStore.delMedication(item.id)
            uni.showToast({ title: '用药记录删除成功' })
          }
        } catch (error) {
          uni.showToast({ title: '删除失败，请重试', icon: 'none' })
          console.error('删除记录失败:', error)
        }
      }
    }
  })
}

/**
 * 查看记录详情
 * @param {Object} item - 记录对象
 * @param {string} type - 记录类型
 */
const viewDetail = (item, type) => {
  if (type === 'medical') {
    recordStore.setSelectedMedicalRecord(item)
  } else {
    recordStore.setSelectedMedication(item)
  }

  dialogType.value = type
  showDialog.value.open()
}

/**
 * 关闭弹窗
 */
const closeDialog = () => {
  addDialog.value.close()
}
</script>


<style lang="scss">
/* 颜色变量 */
$primary-color: #409EFF;
$success-color: #67C23A;
$warning-color: #E6A23C;
$danger-color: #F56C6C;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;

/* 优化详细信息界面样式 */
.medication-card, .medical-card {
  background: linear-gradient(135deg, #e8f5ff, #ffffff);
  border-radius: 24rpx;
  padding: 100rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-4rpx);
    box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.15);
  }

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 32rpx;

    .pill-icon {
      background: $primary-color;
      width: 64rpx;
      height: 64rpx;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 24rpx;
    }

    .card-title {
      font-size: 36rpx;
      font-weight: 600;
      color: $text-primary;
    }
  }

  .card-section {
    margin-bottom: 32rpx;
    padding: 24rpx;
    background: #f9fbfd;
    border-radius: 16rpx;
    border: 1rpx solid #e0e6ed;
    width: 100%;

    .section-header {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;

      .section-title {
        margin-left: 12rpx;
        font-size: 28rpx;
        color: $text-regular;
      }
    }

    .description-text {
      font-size: 26rpx;
      color: $text-regular;
      line-height: 1.6;
    }
  }

  .action-bar {
    display: flex;
    gap: 24rpx;
    margin-top: 32rpx;

    .action-button {
      flex: 1;
      background: rgba($primary-color, 0.1);
      color: $primary-color;
      border-radius: 12rpx;
      padding: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;

      &.delete {
        background: rgba($danger-color, 0.1);
        color: $danger-color;
      }

      &:active {
        transform: scale(0.95);
      }

      uni-icons {
        margin-right: 8rpx;
      }
    }
  }
}

/* 优化全局按钮样式 */
.add-btn, .upload-btn {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s;

  &:hover {
    opacity: 0.9;
  }

  &:active {
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

  uni-icons {
    margin-right: 10rpx;
  }
}

/* 优化选项卡样式 */
.tab-item {
  transition: all 0.3s;

  &.active {
    transform: translateY(-2rpx);
    color: $primary-color;
    font-weight: bold;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 80rpx;
      height: 6rpx;
      background: $primary-color;
      border-radius: 3rpx;
    }
  }
}

/* 优化列表卡片样式 */
.record-card, .medication-card, .report-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:hover {
    transform: translateY(-4rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .date {
      color: #666;
      font-size: 28rpx;
    }

    .hospital, .name, .type {
      color: $primary-color;
      font-size: 28rpx;
      font-weight: 500;
    }
  }

  .diagnosis, .purpose, .institution {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .advice, .details {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 24rpx;
  }

  .file-info {
    display: flex;
    align-items: center;

    .file-name {
      margin-left: 10rpx;
      color: $primary-color;
    }
  }

  .card-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 20rpx;
    border-top: 1rpx solid #eee;

    .action-btn {
      margin-left: 20rpx;
      font-size: 26rpx;
      padding: 8rpx 20rpx;
      border-radius: 8rpx;
      background: #f0f7ff;
      color: $primary-color;

      &.delete {
        color: $danger-color;
        border: 1rpx solid $danger-color;
        background: #fff;
      }
    }
  }
}

/* 悬浮关闭按钮 */
.close-btn {
  position: absolute;
  top: -80rpx;
  right: -20rpx;
  width: 64rpx;
  height: 64rpx;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
  transition: all 0.3s;
  
  &:active {
    transform: rotate(90deg) scale(0.9);
  }
}
</style>

<style lang="scss">
.health-container {
  padding: 20rpx;
  background-color: #f8fafc;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;

  .logo {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }

  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
  }
}

.tabs {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  margin: 20rpx 0;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #666;

    &.active {
      color: #409eff;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 6rpx;
        background: #409eff;
        border-radius: 3rpx;
      }
    }
  }
}

.content {
  flex: 1;
  padding-bottom: 40rpx;
}

.add-btn,
.upload-btn {
  background: #409eff;
  color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  font-size: 28rpx;

  uni-icons {
    margin-right: 10rpx;
  }
}

.record-list,
.medication-list,
.report-list {

  .record-card,
  .medication-card,
  .report-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

    .card-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .date {
        color: #666;
        font-size: 28rpx;
      }

      .hospital,
      .name,
      .type {
        color: #409eff;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .diagnosis,
    .purpose,
    .institution {
      font-size: 30rpx;
      color: #333;
      margin-bottom: 16rpx;
    }

    .advice,
    .details {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 24rpx;
    }

    .file-info {
      display: flex;
      align-items: center;

      .file-name {
        margin-left: 10rpx;
        color: #409eff;
      }
    }

    .card-footer {
      display: flex;
      justify-content: flex-end;
      padding-top: 20rpx;
      border-top: 1rpx solid #eee;

      .action-btn {
        margin-left: 20rpx;
        font-size: 26rpx;
        padding: 8rpx 20rpx;
        border-radius: 8rpx;
        background: #f0f7ff;
        color: #409eff;

        &.delete {
          color: #f56c6c;
          border: 1rpx solid #f56c6c;
          background: #fff;
        }
      }
    }
  }
}

.dialog-content {
  padding: 30rpx;

  .uni-forms-item {
    margin-bottom: 30rpx;
  }
}

.dialog-btn {
  flex: 1;
  padding: 20rpx;
  font-size: 30rpx;

  &.cancel {
    background: #fff;
    color: #666;
    border-top: 1rpx solid #eee;
  }

  &.confirm {
    background: #409eff;
    color: #fff;
    border-top: 1rpx solid #409eff;
  }
}

.upload-btn {
  background: #409eff;
  color: #fff;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  font-size: 28rpx;
  /* 确保按钮可点击 */
  position: relative;
  z-index: 1;

  uni-icons {
    margin-right: 10rpx;
  }

  /* 按下效果 */
  &:active {
    opacity: 0.8;
  }




}
</style>